package com.vinoxm.common.core.handler;

import com.vinoxm.common.base.result.BaseResult;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Log4j2
public class ResponseBodyHandler implements ResponseBodyAdvice<BaseResult> {

    public ResponseBodyHandler() {
        log.info("[ResponseBodyHandler] Initialization");
    }
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return BaseResult.class.isAssignableFrom(returnType.getParameterType());
    }

    @SneakyThrows
    @Override
    public BaseResult beforeBodyWrite(BaseResult baseResult, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info(String.format("[Request return] %s:%s -> %s", serverHttpRequest.getMethod(), serverHttpRequest.getURI().getPath(), (baseResult == null ? "Nothing" : baseResult.toString())));
        return baseResult;
    }
}
